<template>
  <div class="send-message-container">
    <el-card class="message-card">
      <template #header>
        <div class="card-header">
          <span>微信群发消息</span>
        </div>
      </template>

      <el-form :model="messageForm" :rules="rules" ref="messageFormRef" label-width="120px">
        <!-- 发送目标选择 -->
        <el-form-item label="发送目标" prop="isToAll">
          <el-radio-group v-model="messageForm.isToAll">
            <el-radio :label="true">全部用户</el-radio>
            <el-radio :label="false">指定标签</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 标签选择，仅在选择指定标签时显示 -->
        <el-form-item v-if="!messageForm.isToAll" label="用户标签" prop="tagId">
          <el-select v-model="messageForm.tagId" placeholder="请选择用户标签">
            <el-option
              v-for="tag in tags"
              :key="tag.id"
              :label="tag.name"
              :value="tag.id"
            />
          </el-select>
        </el-form-item>

        <!-- 消息内容 -->
        <el-form-item label="消息内容" prop="content">
          <el-input
            v-model="messageForm.content"
            type="textarea"
            :rows="6"
            placeholder="请输入要群发的消息内容"
          />
          <div class="content-tip">注：消息内容不能为空，建议控制在500字以内</div>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="sending">
            发送消息
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { sendMassMessage } from '../api/wechat'

// 表单数据
const messageForm = reactive({
  isToAll: true,
  tagId: '',
  content: ''
})

// 表单校验规则
const rules = {
  content: [
    { required: true, message: '请输入消息内容', trigger: 'blur' },
    { max: 500, message: '消息内容不能超过500字', trigger: 'blur' }
  ],
  tagId: [
    { 
      required: true, 
      message: '请选择用户标签', 
      trigger: 'change',
      validator: (rule, value, callback) => {
        if (!messageForm.isToAll && !value) {
          callback(new Error('请选择用户标签'))
        } else {
          callback()
        }
      }
    }
  ]
}

// 用户标签列表（实际项目中应该从后端获取）
const tags = ref([
  { id: 1, name: '学生' },
  { id: 2, name: '教师' },
  { id: 3, name: '管理员' }
])

const messageFormRef = ref(null)
const sending = ref(false)

// 提交表单
const handleSubmit = async () => {
  if (!messageFormRef.value) return
  
  await messageFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    sending.value = true
    try {
      const response = await sendMassMessage({
        filter: {
          is_to_all: messageForm.isToAll,
          tag_id: messageForm.isToAll ? undefined : messageForm.tagId
        },
        text: {
          content: messageForm.content
        },
        msgtype: 'text'
      })
      
      if (response.errcode === 0) {
        ElMessage.success('消息发送成功')
        // 重置表单
        messageFormRef.value.resetFields()
      } else {
        ElMessage.error(`发送失败：${response.errmsg}`)
      }
    } catch (error) {
      ElMessage.error(error.message || '发送失败，请重试')
    } finally {
      sending.value = false
    }
  })
}
</script>

<style scoped>
.send-message-container {
  padding: 20px;
}

.message-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.content-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}
</style>